// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129

// 指定长度和基数
function getUuid(len, radix) {
	var chars = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
	var uuid = [],
		i;
	radix = radix || chars.length;

	if (len) {
		// Compact form
		for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
	} else {
		var r;
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';

		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | Math.random() * 16;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}
	}

	return uuid.join('');
}
const db = uniCloud.database()

module.exports = {
	_before: function() { // 通用预处理器

	},
	add: async ({
		owner_name
	}) => {
		let enterDB = db.collection('cc_code')
		const code = getUuid(6)

		const detail = await enterDB.where({
			owner_name
		}).get()
		if (detail.data.length) {
			return {
				code: 400,
				msg: '货主已存在',
			}
		}
		const res = enterDB.add({
			owner_name,
			code
		})

		return {
			code: 200,
			msg: '创建成功',
			data: {
				code
			}
		}
	},
	edit({
		owner_name,
		_id
	}) {
		let enterDB = db.collection('cc_code')

		const res = enterDB.where({
			_id
		}).update({
			owner_name
		})
		return {
			code: 200,
			msg: '编辑成功',
		}
	},
	list: () => {
		let enterDB = db.collection('cc_code')
		const res = enterDB.get();
		return res;
	},
	detail: async (id) => {
		let enterDB = db.collection('cc_code')

		if (id) {
			enterDB = enterDB.where({
				_id: id
			})
		}
		const res = await enterDB.get({
			getOne: true,
		})
		return res;
	},
	code: async (code) => {
		let enterDB = db.collection('cc_code')
	
		if (code) {
			enterDB = enterDB.where({
				code
			})
		}
		const res = await enterDB.get({
			getOne: true,
		})
		return res;
	},
	search: async ({owner_name}) => {
		let enterDB = db.collection('cc_code')

		if (owner_name) {
			enterDB = enterDB.where({
				owner_name
			})
		}
		const res = await enterDB.get({
			getOne: true,
		})
		return res;
	},
}